public class Num2 {

    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode res = null;
        ListNode finalRes = null;
        int temp = 0;
        while (l1 != null || l2 != null) {

            int val1 = l1 == null ? 0 : l1.val;
            int val2 = l2 == null ? 0 : l2.val;

            ListNode resNode = null;
            if (val1 + val2 + temp > 9) {
                resNode = new ListNode(val1 + val2 + temp - 10);
                temp = 1;
            } else {
                resNode = new ListNode(val1 + val2 + temp);
                temp = 0;
            }

            if (res == null) {
                res = resNode;
                finalRes = resNode;
            } else {
                res.next = resNode;
                res = res.next;
            }

            l1 = l1 == null ? null : l1.next;
            l2 = l2 == null ? null : l2.next;
        }

        if (temp == 1) {
            res.next = new ListNode(1);
        }

        return finalRes;
    }
}
